package controller;

import java.util.ArrayList;
import java.util.Vector;
import java.util.regex.Pattern;

import dal.JMLDatabase;
import dal.datastore.TableData;
import dto.ColumnDTO;
import dto.RowDTO;

/**
 * @author Stanley
 * 
 */
public class UPDATECommand {
	private String _command;
	private TableData _data;

	public UPDATECommand(String _command, TableData _data) {
		super();
		this._command = _command;
		this._data = _data;
	}

	public UPDATECommand(String _command) {
		super();
		this._command = _command;
	}

	/**
	 * Execute update command
	 * @param indexes 
	 * @return
	 * @throws Exception 
	 */
	public TableData execute(ArrayList<Integer> indexes) throws Exception{
		if(isUpdateCommand()){
			ArrayList<String> strings = parseCommand();
			String key = strings.get(0);
			String values = strings.get(1);
			
			Vector<ColumnDTO> cols = new Vector<>(_data.getColumns());
			int keyIndex = cols.indexOf(new ColumnDTO(key, null));
			if (keyIndex == -1) {
				throw new Exception("Column " + key + " does not exists.");
			}
			if (indexes.size() == 0) {
				for (int i = 0; i < _data.getRows().size(); i++) {
					_data.getRows().get(i).setValueAtIndex(keyIndex, values);
					indexes.add(i);
				}
			} else {
				for (RowDTO row : _data.getRows()) {
					row.setValueAtIndex(keyIndex, values);
				}
			}
			return _data;
		}
		return null;
	}
	
	/**
	 * Parse command
	 * @return
	 */
	public ArrayList<String> parseCommand(){
		Pattern p = Pattern.compile(",|=|\\'");
		return QueryParser.removeAllEmptyString(p.split(_command));
	}

	/**
	 * Validate update command
	 * @return
	 */
	private boolean isUpdateCommand() {
		String operators = "(=|!=|>|<|<=|>=|like|not like)";
		String p = "\\w+\\s*" + operators + "\\s*(\\'\\w+(\\s*\\w+\\s*)*'|(-)?\\d+)";
		return _command.matches(p);
	}
}
